/**
 * create by young (young2f@outlook.com) on 2019/5/6
 */
'use strict';
const StringUtils = require('./stringUtils');
const fs = require('fs');

async function readFile2json(file) {
  if (!fs.existsSync(file)) {
    console.error('readFile2json,file isnot exist', file);
    return undefined;
  }
  const str = await fs.readFileSync(file, 'utf8');
  return StringUtils.str2json(str);
}

async function readFile2str(file) {
  if (!fs.existsSync(file)) {
    console.error('readFile2json,file isnot exist', file);
    return;
  }
  return fs.readFileSync(file, 'utf8');
}

async function writeFile(file, content) {
  if (typeof content === 'object') {
    content = JSON.stringify(content);
  }
  // const Promise = require('bluebird');
  // const writeFile = Promise.promisify(require('fs').writeFile);
  // //  console.log(file);
  // return await writeFile(file, content);
  return fs.writeFileSync(file, content);
}

async function deleteFile(file) {
  if (!fs.existsSync(file)) {
    console.error('deleteFile,file isnot exist', file);
    return 'ok';
  }
  // const Promise = require('bluebird');
  // const deleteFile = Promise.promisify(require('fs').unlink);
  return fs.unlinkSync(file);
}

// async function appendFile(file, content) {
//     const Promise = require('bluebird');
//     const writeFile = Promise.promisify(require('fs').appendFile);
//     //  console.log(file);
//     return await writeFile(file, content);
// }

async function createPath(path) {
  if (fs.existsSync(path)) {
    //   console.log('目录已存在', path)
    return Promise.resolve(true);
  }
  fs.mkdir(path, err => {
    if (err === undefined || err === null) {
      return Promise.resolve(true);
    } else {
      return Promise.reject(err);
    }
  });
}

/**
 * 文件遍历方法
 * @param filePath 需要遍历的文件路径
 */
function listFile(path, fileList) {
  let dirList = fs.readdirSync(path);

  dirList.forEach(function(item) {
    if (fs.statSync(path + '/' + item)
      .isFile()) {
      const json = { path, file: item };
      fileList.push(json);
    }
  });

  dirList.forEach(function(item) {
    if (fs.statSync(path + '/' + item)
      .isDirectory()) {
      listFile(path + '/' + item, fileList);
    }
  });
}

function getFileSize(file) {
  const info = fs.statSync(file);
  const { size } = info;
  return size;
}

module.exports = {
  readFile2json,
  writeFile,
  deleteFile,
  createPath,
  readFile2str,
  getFileSize,
  // appendFile,
  listFile,
};
